<?php

namespace common\widgets\grid;

use yii\helpers\Html;
use yii\grid\GridView as BaseGridView;
use yii\widgets\Pjax;

/**
 * The GridView widget is used to display data in a grid.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class GridView extends BaseGridView {

    /**
     * @var string the default data column class if the class name is not explicitly specified when configuring a data column.
     * Defaults to 'common\widgets\grid\DataColumn'.
     */
    public $dataColumnClass = '\common\widgets\grid\DataColumn';

    /**
     * <div class="caption">
     * 		<i class=" icon-layers font-green"></i>
     * 		<span class="caption-subject font-green sbold uppercase">Validation States</span>                      
     * </div>
     * <div class="actions">
     * 		<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"><i class="icon-cloud-upload"></i></a>
     * 		<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"><i class="icon-wrench"></i></a>
     * 		<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"><i class="icon-trash"></i></a>
     * </div>
     * 
     * @var type 
     */
    public $portletTitle;

    /**
     * @var array the HTML attributes for the portletTitle element.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     * @see portletTitle
     */
    public $portletTitleOptions = ['class' => 'portlet-title'];

    /**
     * @var array the HTML attributes for the grid table element.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $tableOptions = ['class' => 'table table-hover'];

    /**
     * @var boolean whether to show the header section of the grid table.
     */
    public $usePortlet = true;

    /**
     * @var boolean whether to show the header section of the grid table.
     */
    public $showHeader = true;

    /**
     * @var boolean whether to show the footer section of the grid table.
     */
    public $showFooter = true;

    /**
     * @var boolean whether to show the footer section of the grid table.
     */
    public $batchButtons = [];

    /**
     * @var bool whether to place footer after body in DOM if $showFooter is true
     * @since 2.0.14
     */
    public $placeFooterAfterBody = true;

    /**
     * @var boolean whether to show the grid view if [[dataProvider]] returns no data.
     */
    public $showOnEmpty = true;

    /**
     * @var string the HTML display when the content of a cell is empty.
     * This property is used to render cells that have no defined content,
     * e.g. empty footer or filter cells.
     *
     * Note that this is not used by the [[DataColumn]] if a data item is `null`. In that case
     * the [[\yii\i18n\Formatter::nullDisplay|nullDisplay]] property of the [[formatter]] will
     * be used to indicate an empty data value.
     */
    public $emptyCell = '&nbsp;';

    /**
     * @var array the options for rendering the filter error summary.
     * Please refer to [[Html::errorSummary()]] for more details about how to specify the options.
     * @see renderErrors()
     */
    public $filterErrorSummaryOptions = ['class' => 'error-summary'];

    /**
     * @var array the options for rendering every filter error message.
     * This is mainly used by [[Html::error()]] when rendering an error message next to every filter input field.
     */
    public $filterErrorOptions = ['class' => 'help-block'];

    /**
     * @var array the options for rendering every filter error message.
     * This is mainly used by [[Html::error()]] when rendering an error message next to every filter input field.
     */
    public $filterTemplate = false;

    /**
     * @var string the layout that determines how different sections of the list view should be organized.
     * The following tokens will be replaced with the corresponding section contents:
     *
     * - `{summary}`: the summary section. See [[renderSummary()]].
     * - `{errors}`: the filter model error summary. See [[renderErrors()]].
     * - `{items}`: the list items. See [[renderItems()]].
     * - `{sorter}`: the sorter. See [[renderSorter()]].
     * - `{pager}`: the pager. See [[renderPager()]].
     */
    public $layout = '<div class="portlet-body"><div class="table-scrollable">{items}</div></div><div class="portlet-footer">{pager}</div>';
    public $useKeywordSearch = false;

    /**
     * Initializes the grid view.
     * This method will initialize required property values and instantiate [[columns]] objects.
     */
    public function init() {
        $this->renderPortletLayout();
        Html::addCssClass($this->options, 'grid-view');
        parent::init();
    }

    /**
     * Runs the widget.
     */
    public function run() {
        $view = $this->getView();
        GridViewAsset::register($view);
        if ($this->filterModel !== null && $this->useKeywordSearch) {
            if ($this->useKeywordSearch) {
                Pjax::begin(['id' => 'keywordfilter']);
                parent::run();
                Pjax::end();
            } elseif ($this->filterTemplate) {
                echo Html::tag('tr', '<td>' . $this->render('/' . $this->getView()->context->id . '/' . $this->filterTemplate, [
                    'model' => $this->filterModel,
                    'options' => $this->filterRowOptions,
                    'view' => $this->getView()->context,
                ]) . '</td>', $this->filterRowOptions);
                parent::run();
            }
        } else {
            parent::run();
        }
    }

    /**
     * Renders the filter.
     * @return string the rendering result.
     */
    public function renderFilters() {
        if ($this->useKeywordSearch) {
            $this->getView()->params['fastsearch'] = [
                'searchModel' => $this->filterModel,
            ];
        } else {
            return parent::renderFilters();
        }
    }

    /**
     * Renders the portletLayout element.
     * This method will set layout 'portlet'.
     */
    public function renderPortletLayout() {
        if ($this->usePortlet !== false) {
            Html::addCssClass($this->options, 'portlet');
            if (!empty($this->portletTitle)) {
                $this->layout = Html::tag('div', $this->portletTitle, $this->portletTitleOptions) . $this->layout;
            }
        } else {
            $this->layout = "{items}\n{pager}";
        }
    }

    /**
     * Renders the table footer.
     * @return string the rendering result.
     */
    public function renderTableFooter() {
        $cells = [];
        foreach ($this->columns as $column) {
            /* @var $column Column */
            $cells[] = $column->renderFooterCell();
            break;
        }
        $cells[] = Html::tag('td', $this->renderBatchCellContent(), [
            'colspan' => count($this->columns) - 1,
        ]);
        $content = Html::tag('tr', implode('', $cells), $this->footerRowOptions);
        if ($this->filterPosition === self::FILTER_POS_FOOTER) {
            $content .= $this->renderFilters();
        }

        return "<tfoot>\n" . $content . "\n</tfoot>";
    }

    public function renderBatchCellContent() {
        return Html::tag('div', $this->renderBatchButtons() . $this->renderSummary(), [
            'class' => 'table-batch-options'
        ]);
    }

    public function renderBatchButtons() {
        if (empty($this->batchButtons)) {
            return '';
        }
        return Html::tag('div', implode("\n", $this->batchButtons), [
            'class' => 'batch-buttons'
        ]);
    }

}
